// intercept villages
TrvnInterceptorService.installInterceptor( {
	name : "core.Villages",
	isAvailble : function() {
		return true;
	},
	intercept : function(doc) {
		var accountConfig = TrvnCfg.getCurrentAccount();
		if (!accountConfig.villages) {
			accountConfig.villages = new Array();
		}
		if (doc.$G('lright1')) {
			doc.$G('lright1').style.width = 'auto';
		}
		var vlgTable = doc.evaluateXPath(TrvnCfg.queryXPath("villageTable"))[0];
		if (!vlgTable) {
			var infoA = doc.evaluateXPath(TrvnCfg.queryXPath("villageMenuA"))[2];
			if (!infoA) return;
			var uid = infoA.href.toQueryParams().uid;
			if (!uid) return;
			if (!accountConfig.villages[uid]) {
				accountConfig.villages[uid] = {};
			}
			accountConfig.villages[uid].title = accountConfig.name + "的村庄";
			accountConfig.villages[uid].villageId = uid;
			TrvnCfg.getCurrentAccount().currentVillageId = uid;
			return;
		}
		var rows = vlgTable.rows;
		var thisObject = this;
		var sortedVillages = [];
		for (var i = 0;i < rows.length; i++) {
			var a = rows[i].getElementsByTagName("a")[0];
			var vlgId = a.href.toQueryParams().newdid;
			var vlgTitle = rows[i].cells[0].innerHTML.stripTags().substr(8);
			var vlgLocation = rows[i].cells[1].innerHTML.stripTags();
			if (a.className == "active_vl") {
				TrvnCfg.getCurrentAccount().currentVillageId = vlgId;
			}
			if (!accountConfig.villages[vlgId]) {
				sortedVillages[vlgId] = {};
			} else {
				sortedVillages[vlgId] = accountConfig.villages[vlgId];
			}
			sortedVillages[vlgId].title = vlgTitle;
			sortedVillages[vlgId].location = vlgLocation.replace(/[\s\(\)]/g, "");
			sortedVillages[vlgId].villageId = vlgId;

			// add village link pane
			var span = rows[i].cells[0].firstChild;
			span.vlgId = rows[i].cells[0].lastChild.href.toQueryParams().newdid;
			span.style.cursor = "pointer";
			span.style.padding = "0px 2px";
			span.addEventListener('click', function() {
				try {
					var div = thisObject.getLinkPane(doc, this.vlgId);
					div.style.display = "block";
					var top = TrvnStyleUtil.getAbsoluteTop(this);
					TrvnStyleUtil.floatOn(div, this, TrvnStyleUtil.FLOAT_LEFT
							| (top > 400 ? TrvnStyleUtil.ADJUST_BOTTOM : TrvnStyleUtil.ADJUST_TOP));
				} catch (e) {
					TrvnUtils.Logger.error("other.js 401: " + e);
				}
			}, false);
			span.addEventListener('mouseover', function() {
				this.style.border = "1px outset #D0D0D0";
			}, false);
			span.addEventListener('mouseout', function() {
				this.style.border = "0px outset #D0D0D0";
			}, false);

			// add village type icon
			var typeHtml = '-';
			var vlgType = sortedVillages[vlgId].villageType;
			if (vlgType && TrvnData.villageType[vlgType]) {
				typeHtml = TrvnData.villageType[vlgType].html;
			}
			var td = rows[i].insertCell(-1);
			td.className = 'center';
			td.innerHTML = typeHtml;
		}
		accountConfig.villages = sortedVillages;
	},
	villageURLs : [
	/* 市场 */TrvnData.url.marketplace,
	/* 市政厅 */TrvnData.url.townHall,
	/* 集结点 */TrvnData.url.rallyPoint,
	/* 兵营 */TrvnData.url.barracks,
	/* 马厩 */TrvnData.url.stable,
	/* 工场 */TrvnData.url.workshop,
	/* 英雄园 */TrvnData.url.herosMansion,
	/* 铁匠铺 */TrvnData.url.blacksmith,
	/* 军械库 */TrvnData.url.armoury,
	/* 研发所 */TrvnData.url.academy,
	/* 行宫 */TrvnData.url.residence,
	/* 皇宫 */TrvnData.url.palace,
	/* 中心大楼 */TrvnData.url.mainBuilding],
	getLinkPane : function(doc, newdid) {
		var linkDiv;
		if (doc.$G("LINK_PANE")) {
			linkDiv = doc.$G("LINK_PANE");
			linkDiv.innerHTML = "";
		} else {
			linkDiv = doc.$C("div");
			linkDiv.id = "LINK_PANE";
			linkDiv.style.position = "absolute";
			linkDiv.style.zIndex = 99;
			linkDiv.style.backgroundColor = "#FFFFFF";
			linkDiv.style.border = "1px outset #D0D0D0";
			linkDiv.style.display = "none";
			linkDiv.style.padding = "5px 8px";
			doc.body.appendChild(linkDiv);
			doc.addEventListener("mouseup", function() {
				linkDiv.style.display = "none";
			}, false);
		}
		for (var i = 0;i < this.villageURLs.length; i++) {
			linkDiv.appendChild(this.villageURLs[i].toDomA(doc, newdid));
			linkDiv.appendChild(doc.$C("br"));
		}
		return linkDiv;
	}
});
// intercept resource and village type
TrvnInterceptorService.installInterceptor( {
	name : "core.Resource",
	isAvailble : function() {
		return true;
	},
	intercept : function(doc) {
		var tables = doc.evaluateXPath('//div[@id="lres0"]//table');
		if (!tables[0]) return;
		var table = tables[0];
		var cells = table.rows[0].cells;
		var capacity = {};
		var quantity = {};
		var names = ["lumber", "clay", "iron", "crop"];
		for (var i = 1;i < 6; i += 2) {
			var v = cells[i].innerHTML.split("/");
			quantity[names[(i - 1) / 2]] = TrvnUtils.parseNumber(v[0]);
			capacity.warehouse = TrvnUtils.parseNumber(v[1]);
		}
		var v;
		if (cells.length == 7) {
			v = tables[1].rows[0].cells[1].innerHTML.split("/");
		} else {
			v = cells[7].innerHTML.split("/");
		}
		quantity.crop = TrvnUtils.parseNumber(v[0]);
		capacity.granary = TrvnUtils.parseNumber(v[1]);
		quantity.timestamp = new Date().getTime();
		TrvnResourceManager.setCapacity(capacity, TrvnCfg.getCurrentVillage());
		TrvnResourceManager.setQuantity(quantity, TrvnCfg.getCurrentVillage());

		if (!doc.URL.contains("dorf1.php")) return;
		var productivity = {};
		table = doc.evaluateXPath('//div[@id="lrpr"]//table')[0];
		if (!table) return;
		var rows = table.rows;
		for (var i = 0;i < rows.length; i++) {
			productivity[names[i]] = TrvnUtils.parseNumber(rows[i].cells[2].innerHTML.stripTags());
		}
		TrvnResourceManager.setProductivity(productivity, TrvnCfg.getCurrentVillage());

		if (!doc.URL.contains("dorf1.php")) return;
		var typeDiv = doc.evaluateXPath(TrvnData.xPath.villageType)[0];
		if (!typeDiv) return;
		TrvnCfg.getCurrentVillage().villageType = TrvnData.villageType.getType(typeDiv.id).toString();
	}
});
// interceptBuildingTask
TrvnInterceptorService.installInterceptor( {
	name : "core.BuildingTask",
	isAvailble : function() {
		return true;
	},
	intercept : function(doc) {
		if (!doc.URL.contains("dorf1.php") && !doc.URL.contains("dorf2.php")) return;
		var curVlg = TrvnCfg.getCurrentVillage();
		TrvnTaskManager.clearBuildTask(curVlg);
		var buildTable;
		if (doc.URL.contains("dorf1.php")) {
			buildTable = doc.evaluateXPath(TrvnCfg.queryXPath("buildTaskTable1"))[0];
		} else {
			buildTable = doc.evaluateXPath(TrvnCfg.queryXPath("buildTaskTable2"))[0];
		}
		if (!buildTable) {
			return;
		}
		for (var i = 0;i < buildTable.rows.length; i++) {
			var taskId = buildTable.rows[i].cells[0].firstChild.href.toQueryParams().d;
			var taskName = buildTable.rows[i].cells[1].firstChild.nodeValue;
			var tlSpan = buildTable.rows[i].cells[2].getElementsByTagName("span")[0];
			var timeLeft = TrvnUtils.timeToMilliseconds(tlSpan.innerHTML);
			var finishTime = new Date().getTime() + timeLeft;
			TrvnTaskManager.addBuildTask(taskId, taskName, finishTime, curVlg);
		}
	}
});
// intercept activity and research
TrvnInterceptorService.installInterceptor( {
	name : "core.ActivityAndResearch",
	isAvailble : function() {
		return true;
	},
	intercept : function(doc) {
		var index = -1;
		var pad = 0;
		if (doc.pageTitle.contains("军械库")) {
			index = 0;
			pad = 1;
		}
		if (doc.pageTitle.contains("铁匠铺")) {
			index = 1;
			pad = 1;
		}
		if (doc.pageTitle.contains("研发所")) {
			index = 2;
			pad = 1;
		}
		if (doc.pageTitle.contains("市政厅")) {
			index = 3;
		}
		if (index < 0) return;

		var tids = [[TrvnTaskManager.RESEARCH_ARMOUR_TYPE, "armoury"],
				[TrvnTaskManager.RESEARCH_ATTACK_TYPE, "blacksmith"], [TrvnTaskManager.RESEARCH_DEV_TYPE, "academy"],
				[TrvnTaskManager.ACTIVITY_TYPE, "activity"]];
		var curVlg = TrvnCfg.getCurrentVillage();
		TrvnTaskManager.clearTask(curVlg, tids[index][0]);
		var table = doc.evaluateXPath('//div[@id="lmid2"]//table[@class="tbg"]')[1];
		if (!table) {
			return;
		}
		var title = table.rows[1].cells[pad].innerHTML;
		var timeLeft = TrvnUtils.timeToMilliseconds(table.rows[1].cells[1 + pad].innerHTML.stripTags());
		var finishTime = new Date().getTime() + timeLeft;
		TrvnTaskManager.addTask(curVlg, tids[index][0], tids[index][1], [title], finishTime);
	}
});
// intercept destroy task
TrvnInterceptorService.installInterceptor( {
	name : "core.DestroyTask",
	isAvailble : function() {
		return true;
	},
	intercept : function(doc) {
		if (!doc.URL.contains("build.php") || !doc.pageTitle.contains("中心大楼")) return;
		TrvnTaskManager.clearDestroyTask(TrvnCfg.getCurrentVillage());
		var span = doc.$G("timer1");
		if (!span) return;
		var title = span.parentNode.parentNode.cells[1].innerHTML;
		var finishTime = new Date().getTime() + TrvnUtils.timeToMilliseconds(span.innerHTML);
		TrvnTaskManager.addDestroyTask(title, finishTime, TrvnCfg.getCurrentVillage());
	}
});
// intercept plus finish all
TrvnInterceptorService.installInterceptor( {
	name : "other.PlusFinishAll",
	isAvailble : function() {
		return true;
	},
	intercept : function(doc) {
		if (!doc.URL.contains("plus.php")) return;
		var params = doc.URL.toQueryParams();
		if (params.id == 3 && params.a == 7) {
			TrvnUtils.each(TrvnCfg.getCurrentVillage().tasks, function(taskType, tasks) {
				if (taskType == TrvnTaskManager.BUILD_TYPE || taskType == TrvnTaskManager.RESEARCH_DEV_TYPE
						|| taskType == TrvnTaskManager.RESEARCH_ARMOUR_TYPE
						|| taskType == TrvnTaskManager.RESEARCH_ATTACK_TYPE || taskType == TrvnTaskManager.DESTROY_TYPE) {
					TrvnUtils.each(tasks, function(taskId, task) {
						if (task.titles[0].contains("行宫") || task.titles[0].contains("皇宫")) return;
						TrvnTaskManager.finishTask(TrvnCfg.getCurrentVillage(), taskType, taskId, task);
					});
				}
			});
		}
	}
});
// travian history
TrvnInterceptorService.installInterceptor( {
	isAvailble : function() {
		return true;
	},
	intercept : function(doc) {
		// history
		var his = Travian.toolDoc.$G("history");
		if (his.childNodes.length == TrvnCfg.maxHistory) {
			his.removeChild(his.firstChild);
		}
		Travian.toolDoc.addListPaneItem("history", Travian.createToolPaneLink(doc.URL, doc.pageTitle == ""
				? doc.title
				: doc.pageTitle));
		// refresh link and current village
		var params = doc.URL.toQueryParams();
		if (params.newdid) {
			TrvnCfg.getCurrentAccount().currentVillageId = params.newdid;
		}
		Travian.refreshUsefulLinksPane();
		var table = doc.$G('navi_table');
		if (!table) return;
		var cell = table.insertRow(-1).insertCell(-1);
		cell.className = 'menu';
		var addBtn = doc.$C('a');
		addBtn.innerHTML = '添加链接';
		addBtn.href = 'javascript:;';
		addBtn.addEventListener('click', function() {
			var docUrl = doc.URL;
			docUrl += docUrl.indexOf("?") < 0 ? "?" : "&";
			docUrl += "newdid=" + TrvnCfg.getCurrentAccount().currentVillageId;
			var newLink = TrvnUtils.promptLink( {
				title : "链接名",
				link : docUrl
			});
			if (newLink) {
				var curAct = TrvnCfg.getCurrentAccount();
				if (!curAct.usefulLinks) {
					curAct.usefulLinks = new Array();
				}
				curAct.usefulLinks.push( {
					title : newLink.title,
					link : newLink.link
				});
				Travian.refreshUsefulLinksPane();
			}
		}, false);
		cell.appendChild(addBtn);
		var delBtn = doc.$C('a');
		delBtn.innerHTML = '删除链接';
		delBtn.href = 'javascript:;';
		delBtn.addEventListener('click', function() {
			var links = [], selected = {};
			TrvnUtils.each(TrvnCfg.getCurrentAccount().usefulLinks, function(index, link) {
				links.push(link.title + '(' + link.link + ')');
			});
			if (Travian.getPromptService().select(null, TrvnCfg.description, "选择要删除的链接", links.length, links, selected)) {
				TrvnCfg.getCurrentAccount().usefulLinks.splice(selected.value, 1);
				Travian.refreshUsefulLinksPane();
			}
		}, false);
		cell.appendChild(delBtn);
	}
});